<template>
  <div class="activity-container">
    <div class="header">
      <h1>活动管理</h1>
      <el-button type="primary" @click="showCreateDialog = true">创建活动</el-button>
    </div>

    <!-- 搜索筛选 -->
    <el-card style="margin-bottom: 20px;">
      <el-form :model="searchForm" inline>
        <el-form-item label="活动状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="全部" value=""></el-option>
            <el-option label="待开始" value="pending"></el-option>
            <el-option label="已发布" value="published"></el-option>
            <el-option label="进行中" value="ongoing"></el-option>
            <el-option label="已结束" value="completed"></el-option>
            <el-option label="已取消" value="cancelled"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关键词">
          <el-input 
            v-model="searchForm.search" 
            placeholder="请输入活动标题或描述" 
            clearable
            style="width: 300px;"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 活动列表 -->
    <el-card>
      <el-table :data="activities" v-loading="loading" style="width: 100%">
        <el-table-column prop="activity_id" label="ID" width="80"></el-table-column>
        <el-table-column prop="title" label="活动标题" min-width="200"></el-table-column>
        <el-table-column prop="anchor.anchor_name" label="主播" width="120">
          <template #default="{ row }">
            {{ row.anchor?.anchor_name || '未知主播' }}
          </template>
        </el-table-column>
        <el-table-column prop="start_time" label="开始时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.start_time) }}
          </template>
        </el-table-column>
        <el-table-column prop="end_time" label="结束时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.end_time) }}
          </template>
        </el-table-column>
        <el-table-column prop="location" label="活动地点" width="120"></el-table-column>
        <el-table-column prop="current_participants" label="预约人数" width="100">
          <template #default="{ row }">
            {{ row.current_participants || 0 }}/{{ row.max_participants || 0 }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)" type="primary">编辑</el-button>
            <el-button 
              size="small" 
              @click="handleStatusChange(row)"
              :type="getStatusButtonType(row.status)"
              :disabled="row.status === 'completed' || row.status === 'cancelled'"
            >
              {{ getStatusButtonText(row.status) }}
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDelete(row)"
              :disabled="!canDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </el-card>

    <!-- 创建活动对话框 -->
    <el-dialog 
      v-model="showCreateDialog" 
      title="创建活动" 
      width="600px"
      @close="handleCreateDialogClose"
    >
      <el-form 
        :model="createForm" 
        :rules="rules" 
        ref="createFormRef" 
        label-width="120px"
      >
        <el-form-item label="活动标题" prop="title">
          <el-input 
            v-model="createForm.title" 
            placeholder="请输入活动标题"
            maxlength="100"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="活动描述" prop="description">
          <el-input 
            v-model="createForm.description" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入活动描述"
            maxlength="500"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="开始时间" prop="start_time">
          <el-date-picker
            v-model="createForm.start_time"
            type="datetime"
            placeholder="选择开始时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="end_time">
          <el-date-picker
            v-model="createForm.end_time"
            type="datetime"
            placeholder="选择结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="活动地点" prop="location">
          <el-input 
            v-model="createForm.location" 
            placeholder="请输入活动地点"
          ></el-input>
        </el-form-item>
        <el-form-item label="最大参与人数" prop="max_participants">
          <el-input-number 
            v-model="createForm.max_participants" 
            :min="1" 
            :max="10000" 
            style="width: 100%"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" @click="handleCreateSubmit" :loading="creating">创建</el-button>
      </template>
    </el-dialog>

    <!-- 编辑活动对话框 -->
    <el-dialog 
      v-model="showEditDialog" 
      title="编辑活动" 
      width="600px"
      @close="handleEditDialogClose"
    >
      <el-form 
        :model="editForm" 
        :rules="rules" 
        ref="editFormRef" 
        label-width="120px"
      >
        <el-form-item label="活动标题" prop="title">
          <el-input 
            v-model="editForm.title" 
            placeholder="请输入活动标题"
            maxlength="100"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="活动描述" prop="description">
          <el-input 
            v-model="editForm.description" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入活动描述"
            maxlength="500"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="开始时间" prop="start_time">
          <el-date-picker
            v-model="editForm.start_time"
            type="datetime"
            placeholder="选择开始时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="end_time">
          <el-date-picker
            v-model="editForm.end_time"
            type="datetime"
            placeholder="选择结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="活动地点" prop="location">
          <el-input 
            v-model="editForm.location" 
            placeholder="请输入活动地点"
          ></el-input>
        </el-form-item>
        <el-form-item label="最大参与人数" prop="max_participants">
          <el-input-number 
            v-model="editForm.max_participants" 
            :min="1" 
            :max="10000" 
            style="width: 100%"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="活动状态" prop="status">
          <el-select 
            v-model="editForm.status" 
            placeholder="请选择状态" 
            style="width: 100%"
          >
            <el-option label="待开始" value="pending"></el-option>
            <el-option label="已发布" value="published"></el-option>
            <el-option label="进行中" value="ongoing"></el-option>
            <el-option label="已结束" value="completed"></el-option>
            <el-option label="已取消" value="cancelled"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditDialog = false">取消</el-button>
        <el-button type="primary" @click="handleEditSubmit" :loading="editing">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { adminAPI } from '@/api/admin'
import type { FormInstance, FormRules } from 'element-plus'

interface Activity {
  activity_id: number
  title: string
  description: string
  anchor: {
    anchor_name: string
    role?: string
  }
  start_time: string
  end_time: string
  location: string
  max_participants: number
  current_participants: number
  status: string
  created_at: string
  updated_at: string
}

// 响应式数据
const loading = ref(false)
const creating = ref(false)
const editing = ref(false)
const showCreateDialog = ref(false)
const showEditDialog = ref(false)
const createFormRef = ref<FormInstance>()
const editFormRef = ref<FormInstance>()
const currentEditId = ref<number | null>(null)

const activities = ref<Activity[]>([])

const searchForm = reactive({
  status: '',
  search: ''
})

const createForm = reactive({
  title: '',
  description: '',
  start_time: '',
  end_time: '',
  location: '线上',
  max_participants: 100
})

const editForm = reactive({
  title: '',
  description: '',
  start_time: '',
  end_time: '',
  location: '线上',
  max_participants: 100,
  status: 'pending'
})

const rules: FormRules = {
  title: [
    { required: true, message: '请输入活动标题', trigger: 'blur' },
    { min: 2, max: 100, message: '标题长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  start_time: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  end_time: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ],
  max_participants: [
    { required: true, message: '请输入最大参与人数', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择活动状态', trigger: 'change' }
  ]
}

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

// 计算属性：检查当前用户是否是超级管理员
const isSuperAdmin = computed(() => {
  // 这里可以根据用户信息判断，暂时先假设能看到所有活动的就是超级管理员
  return activities.value.some(activity => activity.anchor?.anchor_name !== 'T.测试')
})

// 检查是否可以删除活动
const canDelete = (activity: Activity) => {
  // 超级管理员可以删除任何活动
  if (isSuperAdmin.value) {
    return true
  }
  // 普通用户只能删除没有预约的活动
  return activity.current_participants === 0
}

// 加载活动列表
const loadActivities = async () => {
  try {
    loading.value = true
    console.log('📋 加载活动列表...')
    
    const response = await adminAPI.getActivities({
      page: pagination.current,
      limit: pagination.pageSize,
      ...searchForm
    })
    
    // 兼容不同的响应结构
    let success, data, message
    
    if (response.success !== undefined) {
      success = response.success
      data = response.data
      message = response.message
    } else if (response.data && response.data.success !== undefined) {
      success = response.data.success
      data = response.data.data
      message = response.data.message
    } else {
      success = true
      data = response.data || response
      message = '成功'
    }
    
    if (success) {
      activities.value = data?.activities || data || []
      pagination.total = data?.pagination?.total || data?.total || activities.value.length
      console.log('✅ 活动列表加载成功，数量:', activities.value.length)
    } else {
      throw new Error(message || '数据加载失败')
    }
  } catch (error: any) {
    console.error('❌ 加载活动列表失败:', error)
    ElMessage.error('加载失败: ' + (error.message || '网络错误'))
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadActivities()
}

// 重置搜索
const resetSearch = () => {
  searchForm.status = ''
  searchForm.search = ''
  pagination.current = 1
  loadActivities()
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.current = 1
  loadActivities()
}

// 页码变化
const handlePageChange = (page: number) => {
  pagination.current = page
  loadActivities()
}

// 创建活动提交
const handleCreateSubmit = async () => {
  if (!createFormRef.value) return
  
  try {
    await createFormRef.value.validate()
    creating.value = true
    
    console.log('🎯 提交创建活动:', createForm)
    
    const response = await adminAPI.createActivity(createForm)
    
    let success, message
    
    if (response.success !== undefined) {
      success = response.success
      message = response.message
    } else if (response.data && response.data.success !== undefined) {
      success = response.data.success
      message = response.data.message
    } else {
      success = true
      message = '创建成功'
    }
    
    if (success) {
      ElMessage.success('创建活动成功')
      showCreateDialog.value = false
      resetCreateForm()
      loadActivities()
    } else {
      throw new Error(message || '创建失败')
    }
  } catch (error: any) {
    console.error('❌ 创建活动失败:', error)
    if (error instanceof Error) {
      ElMessage.error('创建失败: ' + error.message)
    }
  } finally {
    creating.value = false
  }
}

// 编辑活动
const handleEdit = async (activity: Activity) => {
  try {
    console.log('✏️ 开始编辑活动:', activity.activity_id)
    currentEditId.value = activity.activity_id
    
    // 直接使用当前行的数据，避免额外的API调用
    Object.assign(editForm, {
      title: activity.title,
      description: activity.description || '',
      start_time: activity.start_time,
      end_time: activity.end_time,
      location: activity.location,
      max_participants: activity.max_participants,
      status: activity.status
    })
    
    showEditDialog.value = true
    console.log('✅ 活动数据填充成功')
  } catch (error: any) {
    console.error('❌ 加载活动详情失败:', error)
    ElMessage.error('加载活动详情失败: ' + (error.message || '网络错误'))
  }
}

// 编辑活动提交
const handleEditSubmit = async () => {
  if (!editFormRef.value || !currentEditId.value) return
  
  try {
    await editFormRef.value.validate()
    editing.value = true
    
    console.log('💾 提交编辑活动:', currentEditId.value, editForm)
    
    const response = await adminAPI.updateActivity(currentEditId.value, editForm)
    
    let success, message
    
    if (response.success !== undefined) {
      success = response.success
      message = response.message
    } else if (response.data && response.data.success !== undefined) {
      success = response.data.success
      message = response.data.message
    } else {
      success = true
      message = '更新成功'
    }
    
    if (success) {
      ElMessage.success('活动更新成功')
      showEditDialog.value = false
      resetEditForm()
      loadActivities()
    } else {
      throw new Error(message || '更新失败')
    }
  } catch (error: any) {
    console.error('❌ 更新活动失败:', error)
    if (error instanceof Error) {
      ElMessage.error('更新失败: ' + error.message)
    }
  } finally {
    editing.value = false
  }
}

// 删除活动
const handleDelete = async (activity: Activity) => {
  try {
    await ElMessageBox.confirm(
      `确定删除活动 "${activity.title}" 吗？此操作不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    )
    
    console.log('🗑️ 开始删除活动:', activity.activity_id)
    
    const response = await adminAPI.deleteActivity(activity.activity_id)
    
    let success, message
    
    if (response.success !== undefined) {
      success = response.success
      message = response.message
    } else if (response.data && response.data.success !== undefined) {
      success = response.data.success
      message = response.data.message
    } else {
      success = true
      message = '删除成功'
    }
    
    if (success) {
      ElMessage.success('活动删除成功')
      loadActivities()
    } else {
      throw new Error(message || '删除失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('❌ 删除活动失败:', error)
      ElMessage.error('删除失败: ' + (error.message || '网络错误'))
    }
  }
}

// 状态变更
const handleStatusChange = async (activity: Activity) => {
  try {
    let newStatus = '';
    let actionText = '';
    
    // 根据当前状态决定下一个状态
    switch (activity.status) {
      case 'pending':
        newStatus = 'published';
        actionText = '发布';
        break;
      case 'published':
        newStatus = 'ongoing';
        actionText = '开始';
        break;
      case 'ongoing':
        newStatus = 'completed';
        actionText = '结束';
        break;
      default:
        ElMessage.warning('该活动状态无法变更');
        return;
    }
    
    await ElMessageBox.confirm(
      `确定要${actionText}这个活动吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await adminAPI.updateActivityStatus(activity.activity_id, newStatus)
    
    let success, message
    
    if (response.success !== undefined) {
      success = response.success
      message = response.message
    } else if (response.data && response.data.success !== undefined) {
      success = response.data.success
      message = response.data.message
    } else {
      success = true
      message = '状态更新成功'
    }
    
    if (success) {
      ElMessage.success(`活动已${actionText}`)
      loadActivities()
    } else {
      throw new Error(message || '状态更新失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('❌ 更新活动状态失败:', error)
      ElMessage.error('状态更新失败: ' + (error.message || '网络错误'))
    }
  }
}

// 重置创建表单
const resetCreateForm = () => {
  Object.assign(createForm, {
    title: '',
    description: '',
    start_time: '',
    end_time: '',
    location: '线上',
    max_participants: 100
  })
  createFormRef.value?.clearValidate()
}

// 重置编辑表单
const resetEditForm = () => {
  Object.assign(editForm, {
    title: '',
    description: '',
    start_time: '',
    end_time: '',
    location: '线上',
    max_participants: 100,
    status: 'pending'
  })
  currentEditId.value = null
  editFormRef.value?.clearValidate()
}

// 对话框关闭处理
const handleCreateDialogClose = () => {
  resetCreateForm()
}

const handleEditDialogClose = () => {
  resetEditForm()
}

// 状态显示工具函数
const getStatusType = (status: string) => {
  const types: { [key: string]: string } = {
    pending: 'info',
    published: 'success',
    ongoing: 'warning',
    completed: '',
    cancelled: 'danger'
  }
  return types[status] || ''
}

const getStatusText = (status: string) => {
  const texts: { [key: string]: string } = {
    pending: '待开始',
    published: '已发布',
    ongoing: '进行中',
    completed: '已结束',
    cancelled: '已取消'
  }
  return texts[status] || status
}

const getStatusButtonText = (status: string) => {
  const texts: { [key: string]: string } = {
    pending: '发布活动',
    published: '开始活动',
    ongoing: '结束活动',
    completed: '已结束',
    cancelled: '已取消'
  }
  return texts[status] || '操作'
}

const getStatusButtonType = (status: string) => {
  const types: { [key: string]: string } = {
    pending: 'success',
    published: 'warning',
    ongoing: 'danger',
    completed: 'info',
    cancelled: 'info'
  }
  return types[status] || 'primary'
}

// 日期格式化
const formatDate = (dateString: string) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleString('zh-CN')
}

// 生命周期
onMounted(() => {
  loadActivities()
})
</script>

<style scoped>
.activity-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

:deep(.el-button--danger) {
  background-color: #f56c6c;
  border-color: #f56c6c;
}

:deep(.el-button--danger:hover) {
  background-color: #f78989;
  border-color: #f78989;
}

:deep(.el-button.is-disabled) {
  opacity: 0.6;
}
</style>